<?php
/**
 * Created by PhpStorm.
 * User: 国小果
 * Date: 2022/11/21
 * Time: 17:50
 */

namespace app\backmanage\controller;

use app\common\model\common\SpreadUser;
use thans\layuiAdmin\facade\AdminsAuth;
use thans\layuiAdmin\facade\Json;
use thans\layuiAdmin\Form;
use thans\layuiAdmin\model\Admins;
use thans\layuiAdmin\Traits\FormActions;
use think\facade\View;
use think\helper\Str;
use think\Request;

class Sale extends Base
{
    use FormActions;

    protected $route_alias = 'sale';
    protected $title = '销售管理';


    public function index(Request $request)
    {
        if ($request->isAjax()) {
            list($where, $order, $page, $limit) = self::buildParams('id|mobile|nickname|code|create_time|update_time');
            $model   = new SpreadUser();
            $where[] = ['status','in',[1,2]];
            $list    = $model->where($where)->page($page, $limit)->order($order)->field('id, mobile,realname,  code, status, leave_time, member_id, create_time, update_time')->order('create_time desc')->select()->toArray();
            $count   = $model->where($where)->count();
            Json::success('获取成功', $list, ['total' => $count,'count' => $count]);
        } else {
            $data          = [];
            $data['cols']  = [
                ['field' => 'id',          'title' => 'ID', 'sort' => true,'width'=>80],
                ['field' => 'code',        'title' => '唯一码','width'=>120],
                ['field' => 'mobile',      'title' => '手机号','width'=>150],
                ['field' => 'realname',      'title' => '销售姓名','width'=>100],
                ['field' => 'status',      'title' => '状态','type'=>"button",'option'=>[[1, '在职', 'normal'],[2, '已离职', 'danger']],'width'=>100],
                ['field' => 'member_id',   'title' => '绑定用户ID','event'=>'get_tags_user' ,'width'=>150],
                ['field' => 'create_time', 'title' => '创建时间','width'=>150],
                ['field' => 'update_time', 'title' => '更新时间','width'=>150],
                ['field' => 'right', 'title' => '操作','toolbar'=>'#barDemo','width'=>200],
            ];
            $data['title'] = $this->title;
            $data['search'][] = ['type'=>'text','field'=>'keyword','desc'=>'请输入标题关键字'];
            $data['search'][] = ['type'=>'select','field'=>'status','desc'=>'状态','option'=>[1=>'在职',2=>'已离职']];

            //url init
            $data['get_tags_user'] = '/backmanage/' . $this->route_alias . '/get_tags_user';
            $data['list_url'] = '/backmanage/' . $this->route_alias . '/index';
            $create_url       = '/backmanage/' . $this->route_alias . '/create';
            $edit_url         = '/backmanage/' . $this->route_alias . '/edit';
            $del_url          = '/backmanage/' . $this->route_alias . '/changeStatus';
            $leave_url          = '/backmanage/' . $this->route_alias . '/changeStatus';
            $poster_url          = '/backmanage/' . $this->route_alias . '/createPoster';
            $sync_url       ='/backmanage/' . $this->route_alias .'/syncSaleData';
            if (AdminsAuth::check($create_url)) {
                $data['create_url'] = $create_url;
            }
            if (AdminsAuth::check($del_url)) {
                $data['del_url'] = $del_url;
            }
            if (AdminsAuth::check($leave_url)) {
                $data['leave_url'] = $leave_url;
            }
            if (AdminsAuth::check($sync_url)){
                $data['sync_url']=$sync_url;
            }
            return View::fetch('sale/index', $data);
        }
    }

    public function changeStatus(){
        $id=request()->param('id');
        $status=request()->param('status');
        if ($status==2){
            $leaveTime=time();
        }
        $ret=SpreadUser::where('id',$id)->update([
            'status'=>$status,
            'update_time'=>time(),
            'leave_time'=>$leaveTime??0
        ]);
        if (!$ret){
            return json(['code'=>-1,'msg'=>'操作失败']);
        }
        $postData['id']=$id;
        $postData['status']=$status;
        //获取当前子系统信息
        $signPackageConfigs=\app\common\model\common\PartitionPackage::getPartitionPackageList();
        foreach ($signPackageConfigs as $signPackageConfig){
            $url = $signPackageConfig['crm_url'].'/backmanage/Spread/changeStatus';
            $postData['is_check_auth']=2;
            $ret = json_decode(httpHelper($url,$postData),true);
            if ($ret['code'] != 0){
                return json(['code' => -100, 'msg' => $ret['msg'] ?? $ret['error_msg']]);
            }
        }

        return json(['code'=>0,'msg'=>'操作成功']);
    }

    public function save(Request $request)
    {
        $model = new SpreadUser();
        list($mobile, $realname) = $request->postMore([
            ['mobile', 0],
            ['realname','']
        ], true);
        //检测手机号是否存在
        $curId=$model->where([
            'mobile' => $mobile,
            'status' => 1,
        ])->value('id');
        if (!$curId){
            //获取本次销售自增ID操作值
            $curId=(int)$model->max('id');
            $curId+=100;

            //获取管理员ID
            $adminModel = new Admins();
            $maxAdminId=$adminModel->max('id');
            $salt     = random_str(20);
            $password = encrypt_password(
                $mobile,$salt
            );
            $adminId=$maxAdminId+100;
            $ret =  $adminModel->insert([
                'id'          => $adminId,
                'name'        => 'XS'.$mobile,
                'salt'        => $salt,
                'password'    => $password,
                'nickname'    => 'XS'.$mobile,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            if (!$ret){
                return json(['code' => -100, 'msg' => '管理员信息保存失败']);
            }
        }else{
            return json(['code' => -100, 'msg' => '该销售信息已存在，如需同步数据请点击同步操作']);
        }

        //获取当前子系统信息
        $signPackageConfigs=\app\common\model\common\PartitionPackage::getPartitionPackageList();
        //获取目前最大值用户ID
        $memberMaxId=0;
        foreach ($signPackageConfigs as $signPackageConfig){
            if (empty($signPackageConfig['crm_url'])){
                return json(['code' => -100, 'msg' => '该分区未配置Crm地址']);
            }
            $db=getSwitchDatabaseModel(
                $signPackageConfig['partition_id'],
                $signPackageConfig['api_mysql_host_name'],
                $signPackageConfig['api_mysql_database'],
                $signPackageConfig['api_mysql_username'],
                $signPackageConfig['api_mysql_password'],
                $signPackageConfig['api_mysql_hostport']
            );
            //获取用户信息
            $memberId=$db->table('member')->max('id');
            $memberMaxId=($memberMaxId<$memberId)?$memberId:$memberMaxId;
        }
        //防止重复添加间隔数
        $memberMaxId+=1000;
        //保存销售信息
        $code=Str::random(9);
        $insert=[
            'id'   =>$curId,
            'mobile' => $mobile,
            'realname' => $realname,
            'create_time' => time(),
            'update_time' => time(),
            'status' => 1,
            'leave_time' => 0,
            'member_id' => $memberMaxId,
            'admin_id' =>$adminId,
            'code'=>$code
        ];
        $ret=$model->insert($insert);
        if (!$ret){
            return json(['code' => -100, 'msg' => '销售信息保存失败']);
        }
        $postData=[
            'sale_id'     =>$curId,
            'mobile'      => $mobile,
            'realname'    => $realname,
            'member_id'   => $memberMaxId,
            'code'        =>$code,
            'admin_id'    =>$adminId,
            'admin_name'  => 'XS'.$mobile,
            'admin_salt'  => $salt,
            'admin_password'=> $password,
            'admin_nickname'=> 'XS'.$mobile,
        ];
        foreach ($signPackageConfigs as $signPackageConfig){
            $url = $signPackageConfig['crm_url'].'/backmanage/Spread/save';
            $postData['is_check_auth']=2;
            $ret = json_decode(httpHelper($url,$postData),true);
            if ($ret['code'] != 0){
                return json(['code' => -100, 'msg' => $ret['msg'] ?? $ret['error_msg']]);
            }
        }
        Json::success('操作成功');
    }

    private function buildForm()
    {
        $model = new SpreadUser();
        $form = new Form($model);
        $form->text()->name('mobile')->label('手机号')->placeholder('手机号')->rules('required');
        $form->text()->name('realname')->label('销售姓名')->placeholder('销售姓名')->rules('required');
        return $form;
    }

    //一键同步销售操作
    public function syncSaleData(){
       $saleId=request()->param('id',0);
       if (empty($saleId)){
           return json(['code' => -100, 'msg' => '销售ID无效']);
       }
        $model = new SpreadUser();
        //检测手机号是否存在
        $sale=$model->where([
            'id' => $saleId,
            'status' => 1,
        ])->find();
        if (empty($sale->id)){
            return json(['code' => -100, 'msg' => '销售ID无效']);
        }
        $sale=$sale->toArray();
        $admin = (new Admins())->where(['id' => $sale['admin_id']])->find();
        $postData=[
            'sale_id'     =>$saleId,
            'mobile'      => $sale['mobile'],
            'realname'    => $sale['realname'],
            'member_id'   => $sale['member_id'],
            'code'        =>$sale['code'],
            'admin_id'    =>$sale['admin_id'],
            'admin_name'  => 'XS'.$sale['mobile'],
            'admin_salt'  => $admin->salt??'',
            'admin_password'=> $admin->password??'',
            'admin_nickname'=> 'XS'.$sale['mobile'],
        ];
        $signPackageConfigs=\app\common\model\common\PartitionPackage::getPartitionPackageList();
        foreach ($signPackageConfigs as $signPackageConfig){
            if (empty($signPackageConfig['crm_url'])){
                return json(['code' => -100, 'msg' => '该分区未配置Crm地址']);
            }
            $db=getSwitchDatabaseModel(
                $signPackageConfig['partition_id'],
                $signPackageConfig['api_mysql_host_name'],
                $signPackageConfig['api_mysql_database'],
                $signPackageConfig['api_mysql_username'],
                $signPackageConfig['api_mysql_password'],
                $signPackageConfig['api_mysql_hostport']
            );
            $ret=$db->table('spread_users')->where([
                'mobile' => $sale['mobile'],
                'status' => 1,
            ])->value('id');
            if ($ret){
                continue;
            }
            $url = $signPackageConfig['crm_url'].'/backmanage/Spread/save';
            $postData['is_check_auth']=2;
            $ret = json_decode(httpHelper($url,$postData),true);
            if ($ret['code'] != 0){
                return json(['code' => -100, 'msg' => $ret['msg'] ?? $ret['error_msg']]);
            }
        }
        Json::success('同步成功');
    }

}